﻿using Common;
using Common.Interfaces;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using ModelDto;
using System.Security.Claims;

namespace WebApplication1.Controllers
{
    [ApiController]
    [Route("api/[controller]/[action]")]
    public class JwtCeshiController : ControllerBase
    {
        private readonly IJwtHelperAppService _jwtHelperAppService;
        private readonly IUserInfoHelper userInfoHelper;
        public JwtCeshiController(IJwtHelperAppService _jwtHelperAppService, IUserInfoHelper userInfoHelper)
        {
            this._jwtHelperAppService = _jwtHelperAppService;
            this.userInfoHelper = userInfoHelper;
        }
        [HttpGet]
        public object Login(string name, string pwd)
        {
            //判断登录逻辑，懒得写
            if (true)
            {
                //数据库获取User信息
                User user = new User();
                user.Name = name;
                user.Role = "2";

                var a = _jwtHelperAppService.CreateToken(user);
                return new { token = a.Item1, guoQiTime = a.Item2 };
            }
            else
            {
                return ("密码错误", DateTime.Now);
            }
        }
        /// <summary>
        /// 测试过滤器
        /// </summary>
        /// <returns></returns>
        [HttpGet]
        //[Authorize("Role")]
        [Authorize]
        //[Authorize(Roles = "1")]
        public string Get()
        {
            var a = HttpContext.User.FindFirst(ClaimTypes.Role);
            var b = HttpContext.User.FindFirst("User");
            var userInfo = userInfoHelper.GetUser();
            string token = HttpContext.Request.Headers["LUserInfo"].ToString();
            if (string.IsNullOrEmpty(token))
            {
                return "系统异常";
            }
            var user = _jwtHelperAppService.ParseJwt(token);
            return "11111111";
        }

        /// <summary>
        /// 刷新token信息，设计思路为返回前端token和token过期时间，前端在请求拦截器上加个判断
        /// 如果距离过期时间相差30分钟就先请求刷新token再用刷新后的token进行请求
        /// </summary>
        /// <returns></returns>
        [HttpGet]
        public object RefreshToken()
        {
            if (HttpContext.Items.TryGetValue("LUserInfo", out var userInfoObj))
            {
                var token = userInfoObj?.ToString();
                var user = _jwtHelperAppService.ParseJwt(token);

                var a = _jwtHelperAppService.CreateToken(user);
                return new { token = a.Item1, guoQiTime = a.Item2 };
            }
            return "系统内部错误";
        }
    }
}
